<?php

/**

 * 统计分析
 * 
 * @access  public 
 * @author  zhangyingheng<zhang_yh@jsumt.com.cn> 
 */

namespace Index\Controller;

use Think\Controller;

class CountController extends BaseController {

    public $webid;
    public function _initialize() {
        parent::_initialize();
        $this->title = '效率分析';
        $webid = M('web')->where('webname="新闻动态"')->getField('id');
        $this->webid = $webid;
    }

    public function index() {
        $userInfo = M('user')->field('USER_ID,USER_NAME,BYNAME,USER_PRIV,USER_PRIV_OTHER,DEPT_ID,DEPT_ID_OTHER,head')->where('USER_ID="' . session('user_id') . '"')->find();
        //判断员工还是领导(含部门领导)
        $privNos = M('user_priv')->where('PRIV_NO > 40')->getField('user_priv', true);
        if (!is_array($privNos)) {
            $privNos[] = $privNos;
        }
        $leader = in_array(session('user_priv'), $privNos) ? 0 : 1;
        //判断是否为公司领导
        $privNos = M('user_priv')->where('PRIV_NO <= 20')->getField('user_priv', true);
        if (!is_array($privNos)) {
            $privNos[] = $privNos;
        }
        $boss = in_array(session('user_priv'), $privNos) ? 1 : 0;

        //本月日志完成情况
        //本月完成数量
        $dMap['USER_ID'] = session('user_id');
        $dMap['SUBJECT'] = array('like', '%' . date('Y-m') . '%');
        $diaryCount = M('diary')->where($dMap)->count();
        //未完成日志数量
        //重新计算2月份休息日
        if (date('Y-m') == date('Y-02')) {
            $weekDays = 17;
        } else {
            $weekDays = getWeekendDays(date('Y-m-01'), date('Y-m-d'));
        }
        $noDiaCount = (date('d') - 1) - ($diaryCount + $weekDays);
        if($noDiaCount < 0){
            $noDiaCount = 0;
        }
        
        //日志完成率
        $diaryEffi = $this->getMonthDiary(1);
        $diaryPercent = $diaryEffi['percent'][1];
        $diary['diff'] = $diaryEffi['percent'][1] - $diaryEffi['percent'][0];
        $diary['abs'] = abs($diary['diff']);

        //本月登录次数
        $workDays = date('d') - $weekDays;   //当月工作日
        $lMap['user_id'] = session('user_id');
        $lMap['login_time'] = array('between', [strtotime(date('Y-m-01 00:00:00')), strtotime(date('Y-m-d H:i:s'))]);
        $loginCount = M('user_login')->where($lMap)->count();
        $loginPercent = round(($loginCount / $workDays), 2) * 100;
        $loginPercent = $loginPercent > 100 ? 100 : $loginPercent;
        //上次登录时间
        unset($lMap['login_time']);
        $maxId = M('user_login')->where($lMap)->max('id');
        $lMap['id'] = array('lt', $maxId);
        $prevLoginTime = M('user_login')->where($lMap)->order('login_time desc')->limit(1)->getField('login_time');

        //本月计划完成情况
        //获取计划类型
        $planTypes = M('plan_type')->order('TYPE_NO')->select();
        //获取个人各类计划百分比
        $percents = $this->userProcessDetail($planTypes);
        //未完成计划数
        $unPlanCount = $this->planCount();
        //当前用户本月全部计划数
        $planCount = $this->planCount(1);

        //流程完成情况
        $runCount = $this->getFlowCount($leader);   //发起和已审批流程数
        $unRunCount = $this->getFlowCount($leader, 0);
        //进行中的流程数
        $fMap['BEGIN_USER'] = session('user_id');
        $fMap['DEL_FLAG'] = 0;
        $fMap['BEGIN_TIME'] = array('between', [date('Y-m-01 00:00:00'), date('Y-m-31 00:00:00')]);
        $fMap['_string'] = ' END_TIME IS NULL';
        $doingFlow = M('flow_run')->where($fMap)->count();
        //已完结的流程数
        unset($fMap['_string']);
        $fMap['END_TIME'] = array('neq', '');
        $finishFlow = M('flow_run')->where($fMap)->count();
        //计算流程效率
        //判断当前用户是否有审批流程
        unset($fMap);
        $fMap['USER_ID'] = session('user_id');
        $fMap['FLOW_PRCS'] = array('neq', 1);
        $fMap['CREATE_TIME'] = array('between', [date('Y-m-01'), date('Y-m-31')]);
        $count = M('flow_run_prcs')->where($fMap)->count();

        if ($count) {
            $flowEffi = $this->getMonthFlow(1);
            $flowEffi['currEffi'] = $flowEffi['data'][1];
            $flowEffi['increase'] = round(($flowEffi['ave'][1] - $flowEffi['ave'][0]) / $flowEffi['ave'][0], 2) * 100;
            $flowEffi['abs'] = abs($flowEffi['increase']) > 100 ? 100 : abs($flowEffi['increase']);
            $this->is_effi = true;
        } else {
            $this->is_effi = false;
        }


        $this->userInfo = $userInfo;    //个人信息
        $this->leader = $leader;    //是否为领导(含公司领导)
        $this->boss = $boss;
        $this->diaryCount = $diaryCount;    //日志数量
        $this->noDiaCount = $noDiaCount;    //未填写日志数量
        $this->diaryPercent = $diaryPercent;    //日志完成率
        $this->percents = $percents;    //各类计划百分比
        $this->planCount = $planCount;  //当月所有计划条数
        $this->unPlanCount = $unPlanCount;  //未完成计划数
        $this->loginPercent = $loginPercent;    //登录率
        $this->prevLoginTime = $prevLoginTime;  //上次登录时间
        $this->runCount = $runCount;    //流程发起数和已审批数
        $this->unRunCount = $unRunCount;    //未审批流程数
        $this->doingFlow = $doingFlow;  //进行中的流程数
        $this->finishFlow = $finishFlow;    //已完结的流程数
        $this->flowEffi = $flowEffi;    //流程效率
        $this->diary = $diary;  //日志差率
        $this->display();
    }

    /*
     * 获取流程信息，员工当月发起数量，领导当月已审批和未审批数量
     * params $type 1已审批  0未审批
     */

    private function getFlowCount($leader, $type = 1) {
        //领导
        $fMap['USER_ID'] = session('user_id');
        $fMap['CREATE_TIME'] = array('between', [date('Y-m-01'), date('Y-m-31')]);
        if ($leader == 1) {
            //领导本月已审批的流程数
            $fMap['FLOW_PRCS'] = array('neq', 1);
            if ($type == 1) {
                $fMap['PRCS_FLAG'] = array('in', [3, 4]);
            } else {
                $fMap['PRCS_FLAG'] = array('in', [1, 2]);
            }
        } else {
            //员工本月发起的流程数
            $fMap['FLOW_PRCS'] = 1;
        }

        $runs = M('flow_run_prcs')->field('RUN_ID,FLOW_PRCS,PRCS_FLAG,CREATE_TIME')->where($fMap)->select();
        //print_r($runs);
        $runCount = 0;
        foreach ($runs as $key => $row) {
            $del = M('flow_run')->where('RUN_ID=' . $row['run_id'])->getField('del_flag');
            if ($del == 0) {
                $runCount ++;
            }
        }
        return $runCount;
    }

    /*
     * 当前用户计划条数
     * params $type 0:未完成 1全部
     * return int   计划条数
     */

    public function planCount($type = 0) {
        //取未完成的计划
        if ($type == 0) {
            $map['SMS_FLAG'] = 0;
        } else {
            //当月所有计划
            $map['_string'] = ' END_DATE between "' . date('Y-m-01') . '" and "' . date('Y-m-31') . '" or END_DATE = "0000-00-00"';
        }

        $leaderId = M('department')->where('DEPT_NAME = "公司领导"')->getField('dept_id');
        if (session('dept_id') == $leaderId) {
            //领导
            $counts = M('plan_type')->order('TYPE_NO')->select();
            $plan = 0;
            foreach ($counts as $key => $row) {
                $map['TYPE'] = $row['type_id'];
                $plan += M('work_plan')->where($map)->count();
            }
        } else {
            //员工
            $where['MANAGER'] = array('like', '%' . session('user_id') . '%');
            $where['PARTICIPATOR'] = array('like', '%' . session('user_id') . '%');
            $where['_logic'] = 'or';
            $map['_complex'] = $where;
            $plan = M('work_plan')->where($map)->count();
        }
        return $plan;
    }

    /*
     * 月流程效率分析
     * param int $ajax  是否ajax获取
     */

    public function getMonthFlow($ajax = 0) {
        //取当月前1个月
        for ($i = 0; $i <= 1; $i++) {
            $months[] = date('Y-m', strtotime("-" . $i . " month"));
        }
        $months = array_reverse($months);

        foreach ($months as $key => $row) {
            $charts['month'][] = $row;    //月
            $map['USER_ID'] = session('user_id');
            $map['PRCS_TIME'] = array('between', getthismonth($row));
            $runIds = M('flow_run_prcs')->where($map)->getField('run_id', true);
            if (!is_array($runIds)) {
                $runIds[] = $runIds;
            }
            $runIds = array_unique($runIds);
            $rMap['DEL_FLAG'] = 0;
            $rMap['RUN_ID'] = array('in', $runIds);
            $ids = M('flow_run')->where($rMap)->getField('run_id', true);
            if (!is_array($ids)) {
                $ids[] = $ids;
            }

            $pMap['RUN_ID'] = array('in', $ids);
            $pMap['USER_ID'] = session('user_id');
            $pMap['PRCS_FLAG'] = array('neq', 1);
            $pMap['PRCS_TIME'] = array('neq', '0000-00-00 00:00:00');
            $data = M('flow_run_prcs')->field('RUN_ID,USER_ID,FLOW_PRCS,PRCS_TIME,DELIVER_TIME,PRCS_FLAG')->where($pMap)->select();

            //计算效率
            $total = 0;
            foreach ($data as $k_data => $r_data) {
                if ($r_data['deliver_time'] == '0000-00-00 00:00:00') {
                    $r_data['deliver_time'] = date('Y-m-d H:i:s');
                }
                $diff = strtotime($r_data['deliver_time']) - strtotime($r_data['prcs_time']);
                $total += $diff;
                $data[$k_data]['diff'] = secsToStr($diff);
            }
            $ave = round($total / count($data), 0);
            $charts['data'][] = secsToStr($ave);
            $charts['ave'][] = $ave;
            $charts['total'][] = $total;
            $charts['count'][] = count($data);
            $charts['minute'][] = secsToStr($ave, 1);
        }
        if ($ajax) {
            return $charts;
        } else {
            $this->ajaxReturn($charts);
        }
    }

    /*
     * 日志效率分析
     */

    public function getMonthDiary($ajax = 0) {
        //取当月前1个月
        for ($i = 0; $i <= 1; $i++) {
            $months[] = date('Y-m', strtotime("-" . $i . " month"));
        }
        $months = array_reverse($months);

        foreach ($months as $key => $row) {
            $charts['month'][] = $row;    //月
            //本月完成数量
            $dMap['USER_ID'] = session('user_id');
            $dMap['SUBJECT'] = array('like', '%' . getthismonth($row, 1) . '%');
            $diaryCount = M('diary')->where($dMap)->count();
            $charts['count'][] = $diaryCount;
            //未完成日志数量
            if ($row == date('Y-m-01')) {
                $end = getthismonth($row, 1) . '-' . date('d');
            } else {
                $end = getthismonth($row, 1) . '-31';
            }
            $weekDays = getWeekendDays(getthismonth($row, 1) . '-01', $end);
            if ($diaryCount != 0) {
                if ($row == date('Y-m-01')) {
                    $charts['percent'][] = round(($diaryCount + $weekDays) / (substr($end, -2) - 1), 2) * 100;
                } else {
                    $charts['percent'][] = round(($diaryCount + $weekDays) / substr($end, -2), 2) * 100;
                }
            } else {
                $charts['percent'][] = 0;
            }
        }
        if ($ajax) {
            return $charts;
        } else {
            $this->ajaxReturn($charts);
        }
    }

    /*
     * 修改流程结束时间，已执行，原先移动端流程结束后没有修改flow_run表中的end_time
     */

    private function saveFlowEndTime() {
        $runs = M('flow_run')->field('RUN_ID,FLOW_ID,BEGIN_USER,END_TIME,DEL_FLAG')->where('END_TIME is null and DEL_FLAG = 0')->select();
        foreach ($runs as $key => $row) {
            //取最大prcs
            $maxPrcs = M('flow_process')->where('FLOW_ID=' . $row['flow_id'])->max('prcs_id');
            $runs[$key]['maxPrcs'] = $maxPrcs;
            //取flow_run_prcs中的已完成的最后步骤
            $lastPrcs = M('flow_run_prcs')->where('RUN_ID=' . $row['run_id'] . ' and PRCS_FLAG = 4')->max('flow_prcs');
            $runs[$key]['lastPrcs'] = $lastPrcs;
            if ($maxPrcs == $lastPrcs) {
                M('flow_run')->where('RUN_ID=' . $row['run_id'])->save(array('END_TIME' => date('Y-m-d H:i:s')));
            }
        }
//print_r($runs);
    }

}
